package com.cloudcc.boot.controller;

import com.cloudcc.boot.entity.mdm.EsbBatchData;
import com.cloudcc.boot.entity.mdm.EsbBatchResponse;
import com.cloudcc.boot.entity.mdm.EsbSingleResponse;
import com.cloudcc.boot.entity.mdm.wbs.CRM_WBS_DO;
import com.cloudcc.boot.entity.mdm.wbs.WbsConvert;
import com.cloudcc.boot.entity.mdm.wbs.WbsEsbSingleData;
import com.cloudcc.boot.enums.SuccessfulOrFailedEnum;
import com.cloudcc.boot.service.WbsToCrmService;
import com.yangzg.cloudcc.openapi.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping(path = "/api/mdm")
public class WbsToCrmController {

    private final WbsToCrmService wbsToCrmService;

    public WbsToCrmController(WbsToCrmService wbsToCrmService) {
        this.wbsToCrmService = wbsToCrmService;
    }

    /**
     * 同步WBS数据到CRM
     *
     * @param esbBatchData esb格式批量数据
     * @return esb格式批量响应
     */
    @PostMapping(value = "/syncWbsToCrm", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<EsbBatchResponse> syncWbsToCrm(@RequestBody EsbBatchData<WbsEsbSingleData> esbBatchData) {
        EsbBatchResponse esbBatchResponse = new EsbBatchResponse(esbBatchData.getBatchId());
        for (WbsEsbSingleData item : esbBatchData.getItems()) {
            EsbSingleResponse esbSingleResponse = new EsbSingleResponse(item.getPkId());
            esbBatchResponse.addItem(esbSingleResponse);
            try {
                log.debug("要同步的WBS数据:{}", JacksonUtils.toJsonString(item));
                CRM_WBS_DO crmWbsDo = WbsConvert.convert(item.getData());
                wbsToCrmService.insertOrUpdate(crmWbsDo);
                esbSingleResponse.setStatus(SuccessfulOrFailedEnum.SUCCESS);
                log.debug("同步WBS数据成功");
            } catch (Exception e) {
                esbSingleResponse.setStatus(SuccessfulOrFailedEnum.FAILURE);
                esbSingleResponse.setMessage(e.getMessage());
                log.error("同步WBS数据失败:{}", e.getMessage(), e);
            }
        }
        return ResponseEntity.ok(esbBatchResponse);
    }


}
